/*
 * Copyright 2011 Drew Wilder-Goodwin
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */
#include "resources.h"
#include "tab.h"
#include "utility.h"
#include <assert.h>

/*
 * Helper function.  Sets all of a RECTs
 * fields to zero.
 */
VOID rect_clear(RECT * rect)
{
    rect->bottom = 0;
    rect->left = 0;
    rect->right = 0;
    rect->top = 0;
}

VOID tab_initialize(Tab * tab, HWND hTab, TabResizeCallback resizeCallback)
{
    tab->hTab = hTab;
    tab->resizeCallback = resizeCallback;
}

VOID tab_control_initialize(TabControl * tc, Tab * tabs, int tabCount)
{
    int tabIndex;
    tc->tabs = tabs;
    tc->tabCount = tabCount;
    tc->current = -1;
    rect_clear(&tc->displayArea);
    for (tabIndex = 0; tabIndex < tabCount; tabIndex++) {
        rect_clear(&tc->tabs[tabIndex].lastDisplayArea);
        tc->tabs[tabIndex].resizeCallback = NULL;
        tc->tabs[tabIndex].hTab = NULL;
    }
}

VOID tab_control_display(TabControl * tc, int selected)
{
    Tab *tab;

    /* Check for overflow */
    assert(selected < tc->tabCount);

    /* Check for redisplay */
    if (selected < 0) {
        selected = tc->current;
    }

    /* Hide current tab */
    if (selected != tc->current && tc->current >= 0) {
        ShowWindow(tc->tabs[tc->current].hTab, SW_HIDE);
    }

    /* Check for empty tab */
    tc->current = selected;
    if (tc->current < 0)
        return;
    tab = &tc->tabs[tc->current];
    if (tab->hTab == NULL) {
        tc->current = -1;
        return;
    }

    /* Show new tab */
    /* Resize if necessary */
    if (!rects_equal(&tab->lastDisplayArea, &tc->displayArea)
            && tab->resizeCallback != NULL) {
        tab->resizeCallback(tab->hTab, tc->displayArea);
    }

    /* Show the properly sized tab */
    ShowWindow(tab->hTab, SW_SHOW);
}
